package controller

import (
	"github.com/kataras/iris/v12"
	"log"
	"shop/src/global"
	"shop/src/model"
	"shop/src/service"
	"strconv"
)

type OrderController struct {
	orderService service.OrderService
}

func (c *OrderController) Get(ctx iris.Context) {
	pn := ctx.URLParam("pageNo")
	ps := ctx.URLParam("pageSize")
	var pageNo = 1
	var pageSize = 20
	var err error
	if ps != "" {
		pageNo, err = strconv.Atoi(pn)
		if err != nil {
			log.Println("pageNo参数错误[" + pn + "]")
			global.WriteError(ctx, 100001, err)
			return
		}
	}
	if ps != "" {
		pageSize, err = strconv.Atoi(ps)
		if err != nil {
			log.Println("pageSize参数错误[" + ps + "]")
			global.WriteError(ctx, 100001, err)
			return
		}
	}

	var task model.Order
	list, err := c.orderService.List(task, pageNo, pageSize)
	global.WriteData(ctx, list)
}

func (c *OrderController) GetBy(ctx iris.Context) {
	id, err := strconv.ParseInt(ctx.URLParam("id"), 10, 64)
	if err != nil {
		global.WriteError(ctx, 100001, err)
		return
	}
	order, err := c.orderService.Get(id)
	if err != nil {
		global.WriteError(ctx, 100001, err)
		return
	}
	global.WriteData(ctx, order)
}

func (c *OrderController) Post(ctx iris.Context) {
	var order model.Order
	err := ctx.ReadJSON(&order)
	if err != nil {
		global.WriteError(ctx, 100001, err)
	}
	id, err := c.orderService.Create(&order)
	global.WriteData(ctx, id)
}

func (c *OrderController) Delete(ctx iris.Context) {
	id, err := strconv.ParseInt(ctx.URLParam("id"), 10, 64)
	if err != nil {
		global.WriteError(ctx, 100001, err)
		return
	}
	err = c.orderService.Delete(id)
	global.WriteData(ctx, nil)
}
